package list.hard;

import list.ListNode;

public class ReverseNodeInKGroup {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0, head);

        ListNode pre = dummy;
        ListNode end = dummy;

        while (end.next != null) {
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
            }
            if (end == null) {
                break;
            }
            ListNode l = pre.next;
            ListNode r = end.next;
            end.next = null;
            // 返回头节点
            pre.next = reverse(l);
            //恢复拼接
            l.next = r;


            pre = l;
            end = pre;
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode node = curr.next;
            curr.next = pre;
            pre = curr;
            curr = node;
        }
        return pre;
    }
}
